
package com.amt.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * @Title: XMLUtils
 * @Package: com.amt.util
 * @Description: TODO(His xml解析)
 * @Author: 吴林
 * @Date: 2020年08月06日 14:41
 * Copyright (c) ©1994-2019 Scjydz.com All Rights Reserved.
 **/
@Slf4j
public class XmlUtil {

    //his返回xml中包含错误标签处理合集 逗号分隔
    private static String error_filter = "UNDEFINED";


    /**
     * @param soap XML字符串
     * @return Map集合
     * @throws DocumentException
     * @description: XML字符串解析方法
     */
    public static Map<String, Object> parse(String soap) throws DocumentException {
        Map<String, Object> maps = new HashMap<>();
//        soap = insteadErrorXmL(soap);
        Document doc = DocumentHelper.parseText(soap);// 报文转成doc对象
        Element root = doc.getRootElement();
        Element PublicMethodResult = root.element("Body").element("PublicMethodResponse").element("PublicMethodResult");
        Element Response = DocumentHelper.parseText(PublicMethodResult.getTextTrim()).getRootElement();
        maps.put("ResultCode", Response.element("ResultCode").getText());
        maps.put("ResultList", Response.element("ResultList"));
        return maps;
    }

    /**
     * @param soap XML字符串
     * @return Map集合
     * @throws DocumentException
     * @description: XML字符串解析方法
     */
    public static Map<String, Object> parse2(String soap,String element1,String element2,String element3,String element4) throws DocumentException {
        Map<String, Object> maps = new HashMap<>();
//        soap = insteadErrorXmL(soap);
        Document doc = DocumentHelper.parseText(soap);// 报文转成doc对象
        Element root = doc.getRootElement();
        Element PublicMethodResult = root.element("Body").element(element1).element(element2);
        Element Response = DocumentHelper.parseText(PublicMethodResult.getTextTrim()).getRootElement();
        maps.put("ResultCode", Response.element("ResultCode").getText());
        if (element4 != null){
            maps.put(element4,Response.element(element4).getText());
        }
        if (element3 != null){
            maps.put("ResultList", Response.element(element3));
        }
        return maps;
    }

    /**
     * @param xml XML字符串
     * @return 处理后xml
     * @description: his返回描述中包含标签，dom4j识别会报错，手动过滤
     */
    public static String insteadErrorXmL(String xml) {
        int begin = -1;
        int end = -1;
        StringBuffer sbXml = new StringBuffer(xml);
        if (StringUtil.isNotEmpty(xml)) {
            String[] errors = error_filter.split(",");
            for (int i = 0; i < errors.length; i++) {
                begin = xml.indexOf(errors[i]);
                end = xml.lastIndexOf(errors[i]);
                int len = errors[i].length();
                if (begin >= 1 && begin == end) {
                    sbXml.replace(begin - 1, end + len + 1, errors[i]);
                }
            }
        }
        return sbXml.toString();
    }

    // ======================================= xml 转 map =======================================

    /**
     * (单层) XML格式字符串转换为Map
     *
     * @param xml XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String xml) {
        InputStream stream = null;
        try {
            Map<String, String> data = new HashMap<>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            return data;
        } catch (Exception e) {
            log.error("运行错误:{}", e);
            return null;
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("运行错误:{}", e);
                    log.error("XML数据转换后的Map 流关闭异常");
                }
            }
        }
    }

    /**
     * Map转成实体对象
     *
     * @param map   map实体对象包含属性
     * @param clazz 实体对象类型
     * @return
     */
    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
        if (map == null) {
            return null;
        }
        T obj = null;
        try {
            obj = clazz.newInstance();

            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                String filedTypeName = field.getType().getName();
                try {
                    if (filedTypeName.equalsIgnoreCase("java.util.date")) {
                        String datetimeStamp = String.valueOf(map.get(field.getName()));
                        if (datetimeStamp.equalsIgnoreCase("null")) {
                            field.set(obj, null);
                        } else {
                            field.set(obj, new Date(Long.parseLong(datetimeStamp)));
                        }
                    } else {
                        field.set(obj, map.get(field.getName()));
                    }
                } catch (IllegalArgumentException e) {
                    field.set(obj, null);
                    log.info(obj + "转换异常{}" + e);
                }
            }
        } catch (Exception e) {
            log.error("运行错误:{}", e);
        }
        return obj;
    }


    /**
     * @param
     * @return
     * @description: Map key 首字母大小写转换
     */
    public static Map<String, Object> transformFirstLetter(Map<String, Object> orgMap) {
        Map<String, Object> resultMap = new HashMap<>();
        if (orgMap == null || orgMap.isEmpty()) {
            return resultMap;
        }
        Set<String> keySet = orgMap.keySet();
        for (String key : keySet) {
            String newKey = key;
            if (Character.isLowerCase(key.charAt(0))) {
                newKey = (new StringBuilder()).append(Character.toUpperCase(key.charAt(0))).append(key.substring(1)).toString();
            } else {
                newKey = new StringBuilder().append(Character.toLowerCase(key.charAt(0))).append(key.substring(1)).toString();
            }
            resultMap.put(newKey, orgMap.get(key));
        }
        return resultMap;
    }


    /**
     * @return
     * @description: 解析his soap报文
     */
    public static Map<String, Object> hisSoapToMap(String soap, String pointNode, int flag) {
//		log.info("\n解析his soap报文：" + soap);
        Map<String, Object> toMap = new HashMap<>();
        if (StringUtils.isBlank(soap)) {
            return toMap;
        }

        toMap = xmlToMap(soap, pointNode, flag);
        //递归提取response节点数组 转为map  key为节点名
        String response = eachMapNode(toMap);
        Map<String, Object> responseMap = xmlToMap(response, pointNode, flag);
//		log.info("\n解析his soap报文结果：" + responseMap.toString());
        return responseMap;
    }

    /**
     * @return
     * @description: 删除标签 处理his中出现 <![CDATA[]]> 箱套问题
     */
    public static String hisRemove(String xml) {
        if (xml != null) {
            StringBuffer buff = new StringBuffer();
            String tag = "<![CDATA[";
            int index = xml.indexOf(tag);
            while (index != -1) {
                buff.append(xml.substring(index + tag.length(), xml.indexOf("]]")));
                index = xml.indexOf(tag, index + tag.length() + 1);
            }
            return buff.toString();
        }
        return xml;
    }

    /**
     * @return
     * @description: 删除标签 处理his中出现 <![CDATA[]]> 箱套问题
     */
    public static String hisRemove(String xml, String startTag, String endTag) {
        if (xml != null) {
            StringBuffer buff = new StringBuffer();
            int index = xml.indexOf(startTag);
            //处理标签
            for (int i = 0; index != -1; i++) {
                int startTagIndex = index + startTag.length();
                if (i == 0) buff.append(xml.substring(0, startTagIndex));//截取头

                buff.append(hisRemove(xml.substring(startTagIndex, xml.indexOf(endTag, startTagIndex))));

                int nextIndex = xml.indexOf(startTag, startTagIndex + 1);
                if (nextIndex != -1) {
                    buff.append(xml.substring(xml.indexOf(endTag, startTagIndex), nextIndex + startTag.length()));
                } else {
                    buff.append(xml.substring(xml.indexOf(endTag, startTagIndex)));
                }
                index = nextIndex;
            }
            return buff.toString();
        }
        return null;
    }

    /**
     * @return
     * @description: elemet 元素封装成map
     */
    public static Map<String, Object> elementToMap(Element element) {
        Map<String, Object> outMap = new HashMap<>();
        if (element != null) {
            recursionUnsleeveXmlToMap(element, outMap);
        }
        return outMap;
    }

    /**
     * @return
     * @description: 递归遍历 map箱套的所有节点 获取不是map类型节点并返回节点值
     */
    public static String eachMapNode(Map<String, Object> toMap) {
        String response = null;
        for (Map.Entry<String, Object> entry : toMap.entrySet()) {
            if (entry.getValue() instanceof Map) {
                response = eachMapNode((Map<String, Object>) entry.getValue());
            } else {
                response = (String) toMap.get(entry.getKey());
            }
        }
        return response;
    }

    /**
     * @param xml       xml字符串
     * @param pointNode 指定节点用list存储
     * @param flag      1：递归调用 所有节点（包括子节点）分装一层map 相同节点名会覆盖
     *                  2：递归调用 所有节点（包括子节点）分装map箱套 多个节点list数据会出现覆盖
     *                  3：递归调用 所有节点（包括子节点）分装map箱套 指定节点用list存储
     *                  指定节点名相同不会覆盖 指定节点名list下数据用map存储
     * @return
     * @describe xml 转 map
     */
    public static Map<String, Object> xmlToMap(String xml, String pointNode, int flag) {
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml.trim());
        } catch (DocumentException e) {
            log.error("xml字符串解析，失败 --> {}", e);
        }
        Map<String, Object> map = new HashMap<>();
        if (null == doc) {
            return map;
        }
        // 获取根元素
        Element rootElement = doc.getRootElement();

        switch (flag) {
            case 1:
                recursionUnsleeveXmlToMap(rootElement, map);
                break;
            case 2:
                recursionXmlToMap(rootElement, map);
                break;
            case 3:
                List<Object> pointList = new ArrayList<>();
                recursionXmlToMapList(rootElement, map, pointNode, pointList);
                break;
            case 4:
                List<Object> pointList2 = new ArrayList<>();
                recursionXmlToMapList2(rootElement, map, pointNode, pointList2);
                break;
        }
        return map;
    }

    /**
     * 1：递归调用 所有节点（包括子节点）分装一层map 相同节点名会覆盖
     *
     * @param element 节点元素
     * @param outMap  用于存储xml数据的map
     */
    @SuppressWarnings("unchecked")
    private static void recursionUnsleeveXmlToMap(Element element, Map<String, Object> outMap) {
        // 得到根元素下的子元素列表
        List<Element> list = element.elements();
        int size = list.size();
        if (size == 0) {
            // 如果没有子元素,则将其存储进map中
            outMap.put(element.getName(), element.getTextTrim());
        } else {
            // 遍历子元素
            list.forEach(childElement -> recursionUnsleeveXmlToMap(childElement, outMap));
        }
    }

    /**
     * 2：递归调用 所有节点（包括子节点）分装map箱套 多个节点list数据会出现覆盖
     *
     * @param element 节点元素
     * @param outMap  用于存储xml数据的map
     */
    @SuppressWarnings("unchecked")
    private static void recursionXmlToMap(Element element, Map<String, Object> outMap) {
        // 得到根元素下的子元素列表
        List<Element> list = element.elements();
        int size = list.size();
        if (size == 0) {
            // 如果没有子元素,则将其存储进map中
            outMap.put(element.getName(), element.getTextTrim());
        } else {
            // innerMap用于存储子元素的属性名和属性值
            Map<String, Object> innerMap = new HashMap<>();
            // 遍历子元素
            list.forEach(childElement -> recursionXmlToMap(childElement, innerMap));
            outMap.put(element.getName(), innerMap);
        }
    }

    /**
     * @param element  节点元素
     * @param outMap   用于存储xml数据的map
     * @param node     指定list存储节点名
     * @param listNode 指定节点的list
     * @description: 3：递归调用 所有节点（包括子节点）分装map箱套 指定节点用list存储
     * 指定节点名相同不会覆盖 指定节点名list下数据用map存储
     */
    private static void recursionXmlToMapList(Element element, Map<String, Object> outMap, String node, List<Object> listNode) {
        // 得到根元素下的子元素列表
        List<Element> list = element.elements();
        int size = list.size();
        if (size == 0) {
            // 如果没有子元素,则将其存储进map中
            outMap.put(element.getName(), element.getTextTrim());
        } else {
            // innerMap用于存储子元素的属性名和属性值
            Map<String, Object> innerMap = new HashMap<>();
            // 遍历子元素
            list.forEach(childElement -> recursionXmlToMapList(childElement, innerMap, node, listNode));
            //指定list节点存放数据
            if (StringUtils.isNotBlank(node) && node.equals(element.getName())) {
                listNode.add(innerMap);
                outMap.put(element.getName(), listNode);
            } else {
                outMap.put(element.getName(), innerMap);
            }
        }


    }

    /**
     * @param element  节点元素
     * @param outMap   用于存储xml数据的map
     * @param node     指定list存储节点名
     * @param listNode 指定节点的list
     * @description: 4：递归调用 所有节点（包括子节点）分装map箱套 指定节点用list存储；指定节点内部还有多个同名节点使用list存储
     * 指定节点名相同不会覆盖 指定节点名list下数据用map存储
     */
    private static void     recursionXmlToMapList2(Element element, Map<String, Object> outMap, String node, List<Object> listNode) {
        // 得到根元素下的子元素列表
        List<Element> list = element.elements();
        int size = list.size();
        if (size == 0) {
            // 如果没有子元素,则将其存储进map中
            outMap.put(element.getName(), element.getTextTrim());
        } else {
            // innerMap用于存储子元素的属性名和属性值
            Map<String, Object> innerMap = new HashMap<>();
            // 遍历子元素
            list.forEach(childElement -> recursionXmlToMapList2(childElement, innerMap, node, listNode));
            //指定list节点存放数据
            if (StringUtils.isNotBlank(node) && node.equals(element.getName())) {
                listNode.add(innerMap);
                outMap.put(element.getName(), listNode);
            } else {
                if (outMap.containsKey(element.getName())) {
                    Object o = outMap.get(element.getName());
                    List<Object> listNode2 = null;
                    if (o instanceof Map) {
                        listNode2 = new ArrayList<>();
                        listNode2.add(o);
                    } else {
                        listNode2 = (List<Object>)o;
                    }
                    listNode2.add(innerMap);
                    outMap.put(element.getName(), listNode2);
                } else outMap.put(element.getName(), innerMap);
            }
        }


    }
    /**
     * @since 2021/9/27 15:07
     * @param xml
     * @param node
     * @param nodeList
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    public static Map<String, Object> xmlToMapOut(String xml, String node, List<Object> nodeList) {

        Map<String, Object> map = new HashMap<>();
        Element element = xmlToElement(xml);
        if (element == null) {
            map.put("error","xml字符串解析失败");
            return map;
        }
        elementToMap(element,map,node,nodeList);
        return map;
    }
    /**
     * @description: 对HIS响应数据进行解析
     * @param xml
     * @return 解析xml数据后的Element对象的根节点对象
     */
    private static Element xmlToElement(String xml){
        if (StringUtils.isBlank(xml)){
            log.error("xml字符串为空");
            return null;
        }

        try {
            Document doc = DocumentHelper.parseText(xml.trim());
            return doc.getRootElement();
        } catch (DocumentException e) {
            log.error("xml字符串解析失败", e);
            return null;
        }
    }
    /**
     * @description: 把xml内容的Element对象元素封装到map中
     * <ul>
     *     <li>map结构：指定的node节点以key-List<Map>结构存放；其他标签以key-value格式存放，剔除了层级关系</li>
     * </ul>
     * @param element xml的element对象
     * @param map xml解析后的容器
     * @param node 指定要以key-list<Map>存放的节点名；允许为空
     * @param nodeList 对应上面的list；允许为空
     */
    public static void elementToMap(Element element, Map<String, Object> map, String node, List<Object> nodeList) {
        // 得到根元素下的子元素列表
        List<Element> list = element.elements();
        int size = list.size();
        if (size == 0) {
            // 如果没有子元素,则将其存储进map中
            map.put(element.getName(), element.getTextTrim());
        } else {
            if (StringUtils.isNotBlank(node) && node.equals(element.getName())) {
                // innerMap用于存储指定标签的属性名和属性值
                Map<String, Object> innerMap = new HashMap<>();
                // 遍历子元素
                list.forEach(childElement -> elementToMap(childElement, innerMap, node, nodeList));
                nodeList.add(innerMap);
                map.put(node,nodeList);
            } else {
                // 遍历子元素
                list.forEach(childElement -> elementToMap(childElement, map, node, nodeList));
            }
        }
    }

    // =========================================map 转 xml================================================

    /**
     * (单层)将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        StringWriter writer = new StringWriter();
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            org.w3c.dom.Document document = documentBuilder.newDocument();
            org.w3c.dom.Element root = document.createElement("xml");
            document.appendChild(root);
            for (String key : data.keySet()) {
                String value = data.get(key);
                if (value == null) {
                    value = "";
                }
                value = value.trim();
                org.w3c.dom.Element filed = document.createElement(key);
                filed.appendChild(document.createTextNode(value));
                root.appendChild(filed);
            }
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            log.info(document.toString());
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
            String output = writer.getBuffer().toString();
            writer.close();
            return output;
        } catch (Exception e) {
            log.error("运行错误:{}", e);
            return null;
        } finally {
            if (writer != null) {
                writer.close();
                log.error("将Map转换为XML格式的字符串 流关闭异常");
            }
        }
    }

    /**
     * (单层)将Map转换为XML格式node 不包含头 的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXmlString(Object data) {
        if (data == null) {
            return new String();
        }
        StringBuffer xmlString = new StringBuffer();
        if (data instanceof Map) {
            Map<Object, Object> dataMap = (Map<Object, Object>) data;
            dataMap.keySet().forEach(key -> {
                if (StringUtils.isNotBlank(key.toString())) {
                    Object value = dataMap.get(key);
                    if (value instanceof Map) {
                        xmlString.append("<" + key + ">");
                        xmlString.append(mapToXmlString(value));
                        xmlString.append("</" + key + ">");
                    } else {
                        xmlString.append("<" + key + ">").append(value).append("</" + key + ">");
                    }
                }
            });
        }
        return xmlString.toString();
    }


    /**
     * (多层)map转换为xml格式字符串
     *
     * @param map     需要转换为xml的map
     * @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
     * @return xml字符串
     */
    public static String multilayerMapToXml(Map<String, Object> map, boolean isCDATA) {
        String parentName = "xml";
        Document doc = DocumentHelper.createDocument();
        doc.addElement(parentName);

        String xml = recursionMapToXml(doc.getRootElement(), parentName, map, isCDATA);
        return formatXML(xml);
    }

    /**
     * multilayerMapToXml核心方法，递归调用   his 请求前缀
     *
     * @param element 节点元素
     * @param method  根元素属性名
     * @param map     需要转换为xml的map
     * @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
     * @return xml字符串
     */
    @SuppressWarnings("unchecked")
    private static String recursionHisMapToXml(Element element, String method, Map<String, Object> map, boolean isCDATA) {
        Element xmlElement = element;
        if (StringUtil.isNotEmpty(method)) {
            xmlElement = element.element(method);
        }
        Element finalXmlElement = xmlElement;
        map.keySet().forEach(key -> {
            Object obj = map.get(key);
            if (obj instanceof Map) {
                recursionMapToXml(finalXmlElement, key, (Map<String, Object>) obj, isCDATA);
            } else {
                String value = obj == null ? "" : obj.toString();
                if (isCDATA) {
                    finalXmlElement.addElement(key).addCDATA(value);
                } else {
                    finalXmlElement.addElement(key).addText(value);
                }
            }
        });
        return element.asXML();
    }

    /**
     * multilayerMapToXml核心方法，递归调用
     *
     * @param element    节点元素
     * @param parentName 根元素属性名
     * @param map        需要转换为xml的map
     * @param isCDATA    是否加入CDATA标识符 true:加入 false:不加入
     * @return xml字符串
     */
    @SuppressWarnings("unchecked")
    private static String recursionMapToXml(Element element, String parentName, Map<String, Object> map, boolean isCDATA) {
        Element xmlElement = element;
        if (StringUtil.isNotEmpty(parentName)) {
            xmlElement = element.addElement(parentName);
        }
        Element finalXmlElement = xmlElement;
        map.keySet().forEach(key -> {
            Object obj = map.get(key);
            if (obj instanceof Map) {
                recursionMapToXml(finalXmlElement, key, (Map<String, Object>) obj, isCDATA);
            } else {
                String value = obj == null ? "" : obj.toString();
                if (isCDATA) {
                    finalXmlElement.addElement(key).addCDATA(value);
                } else {
                    finalXmlElement.addElement(key).addText(value);
                }
            }
        });
        return finalXmlElement.asXML();
    }

    /**
     * 格式化xml,显示为容易看的XML格式
     *
     * @param xml 需要格式化的xml字符串
     * @return
     */
    public static String formatXML(String xml) {
        String requestXML = null;
        try {
            // 拿取解析器
            SAXReader reader = new SAXReader();
            Document document = reader.read(new StringReader(xml));
            if (null != document) {
                StringWriter stringWriter = new StringWriter();
                // 格式化,每一级前的空格
                OutputFormat format = new OutputFormat("    ", true);
                // xml声明与内容是否添加空行
                format.setNewLineAfterDeclaration(false);
                // 是否设置xml声明头部
                format.setSuppressDeclaration(false);
                // 是否分行
                format.setNewlines(true);
                XMLWriter writer = new XMLWriter(stringWriter, format);
                writer.write(document);
                writer.flush();
                writer.close();
                requestXML = stringWriter.getBuffer().toString();
            }
            return requestXML;
        } catch (Exception e) {
            log.error("格式化xml，失败 --> {}", e);
            return null;
        }
    }

    public static void main(String[] args) throws DocumentException {

    }
}
